tmpnam関数は、作業用ファイルの名前(パス名)を生成します。名前を生成してから、ファイルをオープンする間に、他のプロセスにより同じ名前が使われる可能性があるため、この関数はできるだけ使用しない方がよいでしょう。同等の機能のtmpfile関数の使用をお薦めします。
#include <stdio.h>
char *tmpnam(char *s);
*sは生成した作業用ファイルの名前を格納する領域を指定します。NULLを指定した場合は、内部的な領域が使用されます。
戻り値として、正常に処理できた場合は、作業用ファイルの名前を、エラーの場合はNULLの値を返します。
プログラム 例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *tmp_fp;
FILE *in_fp;
FILE *out_fp;
char path[100];
char buff[1024];
char *tmp_path;
/* 作業用ファイルのパス名を生成して、オープン */
tmp_path = tmpnam(NULL);
if ((tmp_fp = fopen(tmp_path, 'w+')) == NULL) {
printf('作業用ファイルがオープンできません\n');
exit(1);
}
while (1) {
printf('入力ファイルのパス名を入力してください ==> ');
scanf('%s', path);
if (strcmp(path, 'end') != 0) {
if ((in_fp = fopen(path, 'r')) != NULL) {
while (fgets(buff, 1024, in_fp) != NULL) {
fputs(buff, tmp_fp);
}
fclose(in_fp);
}
else {
printf('%sファイルがオープンできません\n', path);
}
}
else {
break;
}
}
printf('マージ出力するファイルのパス名を入力してください ==> ');
scanf('%s', path);
if ((out_fp = fopen(path, 'w')) != NULL) {
/* 作業用ファイルのファイルオフセットをファイルの先頭に戻す */
rewind(tmp_fp);
while (fgets(buff, 1024, tmp_fp) != NULL) {
fputs(buff, out_fp);
}
fclose(out_fp);
}
else {
printf('%sファイルがオープンできません\n', path);
}
/* 作業用ファイルを閉じて、削除 */
fclose(tmp_fp);
remove(tmp_path);
return 0;
}
例の実行結果
$ cat temp_1.txt Hello World!!. Bye. $ $ cat temp_2.txt 0010067.500175.500021.92 0020088.000187.800024.95 0030054.300164.000020.19 $ $ ./tmpnam.exe 入力ファイルのパス名を入力してください ==> temp_1.txt 入力ファイルのパス名を入力してください ==> temp_2.txt 入力ファイルのパス名を入力してください ==> end マージ出力するファイルのパス名を入力してください ==> temp_mrg.txt $ $ cat temp_mrg.txt Hello World!!. Bye. 0010067.500175.500021.92 0020088.000187.800024.95 0030054.300164.000020.19 $